const express = require("express");
const router = express.Router();
const { success, fail } = require("../utils/response");
const authMiddleware = require("../middlewares/auth");
const jwt = require("jsonwebtoken");
const JWT_SECRET = process.env.JWT_SECRET; // 或者直接使用你的密钥
const { Item, Favorite } = require("../models"); // 引入图片模型
const { getSignedUrl } = require("../utils/oss"); // 确保你已经正确引入签名工具

// 创建商品
router.post("/create", authMiddleware, async (req, res) => {
    const {
        title,
        description,
        price,
        imageUrls,
        categoryId,
        labelConfig,
        is_top,
        is_face,
        person_name,
        person_phone

    } = req.body;

    const userId = req.userId;

    console.log('[item] 创建商品请求:', { title, userId });

    try {
        const item = await Item.create({
            title,
            description,
            price,
            image_urls: imageUrls || [],
            categoryId,
            userId,
            label_config: labelConfig || [],
            is_top,
            is_face,
            person_name,
            person_phone
        });

        console.log('[item] 商品创建成功:', item.toJSON());
        return success(res, "商品发布成功", item);
    } catch (err) {
        console.error('[item] 商品发布失败:', err);
        return fail(res, "发布失败", 500);
    }
});


// 获取商品列表（分页）

const { Op } = require("sequelize");

router.post("/list", async (req, res) => {
    const { page = 1, pageSize = 10, categoryId, userId, title } = req.body;
    const offset = (page - 1) * pageSize;
    console.log('[item] 获取商品列表:', { page, pageSize, categoryId, userId, title });

    // 解析 token 获取当前用户 ID
    const authHeader = req.headers.authorization || req.headers.token || "";
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
        return fail(res, "未提供有效的 Token", 401);
    }

    let currentUserId;
    try {
        const token = authHeader.split(" ")[1];
        const decoded = jwt.verify(token, JWT_SECRET);
        currentUserId = decoded.userId;
    } catch (err) {
        console.error("[item] Token 解析失败:", err.message);
        return fail(res, "Token 无效或已过期", 401);
    }

    // 查询条件
    const whereClause = {};

    if (categoryId) {
        whereClause.categoryId = categoryId;
    }

    if (userId === 'mine') {
        whereClause.userId = currentUserId; // 我的商品
    } else {
        whereClause.status = 1; // 上架的商品
    }

    // 模糊搜索
    if (title && title.trim() !== '') {
        whereClause[Op.or] = [
            { title: { [Op.like]: `%${title}%` } },
            { description: { [Op.like]: `%${title}%` } },
            { label_config: { [Op.like]: `%${title}%` } },
            { person_name: { [Op.like]: `%${title}%` } }
        ];
    }

    try {
        const { count, rows } = await Item.findAndCountAll({
            where: whereClause,
            limit: Number(pageSize),
            offset: Number(offset),
            order: [
                ['is_top', 'DESC'],
                ['updatedAt', 'DESC']
            ],
        });

        const signedList = rows.map(item => {
            const data = item.toJSON();
            if (Array.isArray(data.image_urls)) {
                data.signed_image_urls = data.image_urls.map(key => {
                    try {
                        return getSignedUrl(key);
                    } catch (err) {
                        console.error('[item] 生成签名失败:', key, err);
                        return null;
                    }
                });
            } else {
                data.signed_image_urls = [];
            }
            return data;
        });

        console.log('[item] 商品列表返回:', { total: count, count: signedList.length });
        return success(res, "", { total: count, list: signedList });
    } catch (err) {
        console.error('[item] 获取商品列表失败:', err);
        return fail(res, "获取失败", 500);
    }
});


// 获取商品详情
router.post("/detail", async (req, res) => {
    const { id } = req.body;
    if (!id) return fail(res, "缺少商品 ID");

    try {
        const item = await Item.findByPk(id);
        if (!item) {
            console.warn('[item] 商品不存在:', id);
            return fail(res, "商品不存在", 404);
        }

        // 转换为纯对象，避免修改模型实例
        const itemData = item.get({ plain: true });

        // 默认未收藏
        itemData.isFavorite = false;

        // 1. 获取当前用户 userId（通过 token）
        const authHeader = req.headers.authorization || req.headers.token;
        if (authHeader && authHeader.startsWith('Bearer ')) {
            try {
                const token = authHeader.split(' ')[1];
                const payload = jwt.verify(token, process.env.JWT_SECRET || 'secret');
                const userId = payload.userId;

                // 2. 查询收藏关系（包括软删除）
                const favorite = await Favorite.findOne({
                    where: {
                        userId,
                        itemId: id
                    },
                    paranoid: false
                });

                if (favorite && !favorite.deletedAt) {
                    itemData.isFavorite = true;
                }
            } catch (err) {
                console.warn('[item] token 无效，跳过收藏判断:', err.message);
            }
            // 不返回错误，未登录时默认 isFavorite = false 即可
        }

        // 处理图片签名
        const imageUrls = Array.isArray(itemData.image_urls) ? itemData.image_urls : [];
        itemData.signed_image_urls = await Promise.all(
            imageUrls.map(async (key) => {
                if (!key) return null;
                try {
                    return await getSignedUrl(key);
                } catch (err) {
                    console.error('[item] 生成签名失败:', key, err);
                    return null;
                }
            })
        ).then(results => results.filter(url => url !== null));

        console.log('[item] 商品详情返回:', itemData);
        return success(res, "获取成功", itemData);
    } catch (err) {
        console.error('[item] 获取商品详情失败:', err);
        return fail(res, "服务器错误", 500);
    }
});


// 更新商品
router.post('/update', authMiddleware, async (req, res) => {
    const { id, title, description, price, categoryId, userId, status, imageUrls, labelConfig, is_top, is_face, person_name,
        person_phone } = req.body;
    console.log('[item] 商品更新请求:', { id, title, userId });

    if (!id || !title) {
        return res.status(400).json({ code: 400, message: '商品 ID 和标题不能为空' });
    }

    try {
        const item = await Item.findByPk(id);
        if (!item) {
            console.warn('[item] 待更新商品不存在:', id);
            return res.status(404).json({ code: 404, message: '商品不存在' });
        }

        if (item.userId !== userId) {
            console.warn('[item] 非法修改他人商品，当前用户:', userId, '商品用户:', item.userId);
            return res.status(403).json({ code: 403, message: '无权修改该商品' });
        }

        item.title = title;
        item.description = description || '';
        item.price = price;
        item.categoryId = categoryId;
        item.status = status;
        item.image_urls = imageUrls;
        item.label_config = labelConfig || [];
        item.is_top = is_top
        item.is_face = is_face
        item.person_name = person_name
        item.person_phone = person_phone
        await item.save();

        console.log('[item] 商品更新成功:', item.toJSON());
        res.json({ code: 200, message: '商品更新成功', data: item });
    } catch (error) {
        console.error('[item] 商品更新失败:', error);
        res.status(500).json({ code: 500, message: '商品更新失败', error: error.message });
    }
});
// 下架商品
router.post("/off-shelf", authMiddleware, async (req, res) => {
    const { id, userId, status } = req.body;
    console.log('[item] 上下架商品请求:', { id, userId, status });

    if (!id) return fail(res, "缺少商品 ID");

    try {
        const item = await Item.findByPk(id);
        if (!item) {
            console.warn('[item] 待操作商品不存在:', id);
            return fail(res, "商品不存在", 404);
        }

        // 判断是否是当前用户的商品
        if (item.userId !== userId) {
            console.warn('[item] 非法操作他人商品，当前用户:', userId, '商品用户:', item.userId);
            return fail(res, "无权操作该商品", 403);
        }

        item.status = status; // 设置为上下架状态
        await item.save();

        console.log(`[item] 商品${status === 1 ? "上架" : "下架"}成功:`, id);
        return success(res, status === 1 ? "上架成功" : "下架成功");
    } catch (err) {
        console.error('[item] 操作失败:', err);
        return fail(res, "操作失败", 500);
    }
});
// 删除商品（软删除）
router.post("/delete", authMiddleware, async (req, res) => {
    const { id, userId } = req.body;
    console.log('[item] 删除商品请求:', { id, userId });

    if (!id) return fail(res, "缺少商品 ID");

    try {
        const item = await Item.findByPk(id);
        if (!item) {
            console.warn('[item] 待删除商品不存在:', id);
            return fail(res, "商品不存在", 404);
        }

        if (item.userId !== userId) {
            console.warn('[item] 非法删除他人商品，当前用户:', userId, '商品用户:', item.userId);
            return fail(res, "无权删除该商品", 403);
        }

        // 使用 Sequelize 软删除（会设置 deletedAt 字段）
        await item.destroy();
        console.log('[item] 商品软删除成功:', id);

        return success(res, "删除成功");
    } catch (err) {
        console.error('[item] 删除商品失败:', err);
        return fail(res, "删除失败", 500);
    }
});

module.exports = router;
